package com.atzongmaotan.datastructures;

import java.util.ArrayList;

/**
 * ClassName:    SpareArray
 * Package:  com.atzongmaotan.datastructures
 * Description:
 *
 *
 * @Author: interface
 * @Create: 2024/9/29 - 下午6:28
 * @Version: v1.0
 */
public class SpareArray {
    public static void main(String[] args) {
        int chessArray [][] = new int[10][11];
        chessArray[1][2] = 1;
        chessArray[2][3] = 2;
        chessArray[4][5] = 3;
        //spareArrayPrint(chessArray);
        int[][] spareArray = createSpareArray(chessArray);
        spareArrayPrint(spareArray);
        int[][] normalArray = spareArrayTransForNomarl(spareArray);
        spareArrayPrint(normalArray);


    }
    public static void spareArrayPrint(int [][] array) {
        for (int[] ints : array) {
            for (int data : ints) {
                System.out.printf("%d\t", data);
            }
            System.out.println();
        }
    }
    public static int[][] createSpareArray(int [][] array) {
        int sum = calculateNotZero(array);
        int [][] spareArray = new int[sum+1][3];
        // 给稀疏数组赋值
        spareArray[0][0] = array.length;
        spareArray[0][1] = array[0].length;
        spareArray[0][2] = sum;
        int count = 0;
        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < array[i].length; j++) {
                if (array[i][j] != 0) {
                    count++;
                    spareArray[count][0] = i;
                    spareArray[count][1] = j;
                    spareArray[count][2] = array[i][j];
                }
            }
        }
        return spareArray;
    }
    public static int calculateNotZero(int [][] array) {
        int sum = 0;
        for (int[] ints : array) {
            for (int data : ints) {
                if (data != 0) {
                    sum++;
                }
            }
        }
        return sum;
    }
    public static int[][] spareArrayTransForNomarl(int [][] spareArray) {
        int rowNumber = spareArray[0][0];
        int colNumber = spareArray[0][1];
        int[][] normalArray = new int[rowNumber][colNumber];
        for (int i = 1; i < spareArray.length; i++) {
            normalArray[spareArray[i][0]][spareArray[i][1]] = spareArray[i][2];
        }
        return normalArray;
    }
}
